package cn.zy.user.service.impl;

import cn.zy.basic.exception.BusinessException;
import cn.zy.basic.util.Md5Utils;
import cn.zy.basic.util.StrUtils;
import cn.zy.user.domain.Logininfo;
import cn.zy.user.domain.User;
import cn.zy.user.mapper.LogininfoMapper;
import cn.zy.user.mapper.UserMapper;
import cn.zy.user.service.IUserService;
import cn.zy.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;


    @Override
    public void phoneRegister(Map<String, String> map)  {
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String pwd = map.get("pwd");
        String rePwd = map.get("rePwd");

        //一.校验
        //1.空值
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode) ||
                StringUtils.isEmpty(pwd) || StringUtils.isEmpty(rePwd) ){
            throw new BusinessException("信息不能为空");
        }
        //2.密码是否一致
        if(!pwd.equals(rePwd)){
            throw new BusinessException("两次密码不一致");
        }
        //3.手机验证码是否过期,是否正确
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if(obj==null){
            throw new BusinessException("手机验证码过期!!!");
        }
        //redis中手机验证码的存储格式[业务键:手机号码 - 验证码:时间戳]
        if(!phoneCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("手机验证码错误!!!");
        }

        //二.添加到数据库
        //当将一个对象转换成另外一个对象的时候,而且代码量多的时候就使用obj2Obj
        User user = map2User(map);
        Logininfo logininfo =user2Logininfo(user);
        //1.先添加t_logininfo
        logininfoMapper.save(logininfo);
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

    }

    @Override
    public void emailRegister(Map<String, String> map) throws MessagingException {
        String email = map.get("email");
        String pwd = map.get("pwd");
        String rePwd = map.get("rePwd");


        //一.校验
        //1.空值
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(pwd) ||
                StringUtils.isEmpty(rePwd)){
            throw new BusinessException("信息不能为空");
        }
        //2.密码是否一致
        if(!pwd.equals(rePwd)){
            throw new BusinessException("两次密码不一致");
        }
        //3.是否注册过
        //当前邮箱是否入驻过
        User eUser = userMapper.loadByEmail(email);
        if(eUser != null){
            throw new BusinessException("当前邮箱已经注册过,请直接登录.忘记密码请联系管理员!!!");
        }

        //二.添加到数据库
        //当将一个对象转换成另外一个对象的时候,而且代码量多的时候就使用obj2Obj
        User user = emap2User(map);
        Logininfo logininfo =euser2Logininfo(user);
        //1.先添加t_logininfo
        logininfoMapper.save(logininfo);
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);



        //三.发送邮件
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("1160898405@qq.com");//平台的邮箱
        helper.setSubject("店铺激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        //http://172.16.6.244:8080/shop/active/局域网id,可以改成http://127.0.0.1:8080/shop/active/
        helper.setText("<h1>你的账号已经注册!!!</h1>" +
                "<a href='http://127.0.0.1:8080/user/active/"+user.getId()+"'>点击该链接激活</a>",true);
        //收件人
        helper.setTo(user.getEmail());//改邮件是店长的邮箱 - 真实有效
        javaMailSender.send(mimeMessage);

    }

    @Override
    public void active(Long id) {
        User user = userMapper.loadById(id);
        user.setState(1);
        userMapper.update(user);

        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        logininfo.setDisable(true);
        logininfoMapper.update(logininfo);

    }

    private Logininfo euser2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //根据属性同名原则
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//用户手机号注册
        logininfo.setDisable(false);//手机注册默认启用
        return logininfo;
    }

    private User emap2User(Map<String, String> map) {
        User user = new User();
        String email = map.get("email");
        user.setUsername(email);
        user.setEmail(email);
        //生成32位随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(map.get("emailPwd") + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(0);

        return user;
    }


    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //根据属性同名原则
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//用户手机号注册
        logininfo.setDisable(true);//手机注册默认启用
        return logininfo;
    }

    private User map2User(Map<String, String> map) {
        User user = new User();
        String phone = map.get("phone");
        user.setUsername(phone);
        user.setPhone(phone);
        //生成32位随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(map.get("pwd") + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);

        return user;
    }

    @Transactional
    @Override
    public void save(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //先添加logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);//获取到自增ID

        //添加user的数据
        user.setLogininfoId(logininfo.getId());
        super.save(user);
    }

    @Transactional
    @Override
    public void del(Long id) {
        //先查询登陆信息id
        User user = userMapper.loadById(id);

        //删除user
        super.del(id);

        //删除logininfo
        logininfoMapper.del(user.getLogininfoId());
    }

    @Transactional
    @Override
    public void update(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        User oldUser = userMapper.loadById(user.getId());//loginfo_id

        //修改user信息
        user.setLogininfoId(oldUser.getLogininfoId());
        super.update(user);

        //修改登陆信息
        Logininfo oldLogininfo = logininfoMapper.loadById(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        //设置会以前的id - 进行修改
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }

    @Override
    @Transactional
    public void patchDelete(List<Long> ids) {
        for (Long id : ids) {
            del(id);
        }
    }
}
